package com.lv.filter;

import cn.hutool.core.util.StrUtil;
import com.lv.common.untils.RedisCache;
import com.lv.common.untils.TokenUntil;
import com.lv.service.impl.UserDetailServiceImpl;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * token校验过滤器
 * </p>
 *
 * @Author: 凉薄
 * @Date: 2022/01/08/14:01
 * @Description:
 */
public class TokenAuthFilter extends BasicAuthenticationFilter {
    @Autowired
    UserDetailServiceImpl userDetailService;
    @Autowired
    TokenUntil tokenUntil;
    @Autowired
    RedisCache redisCache;

    @Value("${jwt.header}")
    private String header;
    public TokenAuthFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token=request.getHeader(header);
        if(StrUtil.isBlankOrUndefined(token)||token.equals("Basic Og==")){
            chain.doFilter(request,response);
            return;
        }

        Claims claims = tokenUntil.parserToken(token);
        if(claims==null){
            throw new JwtException("非法token");
        }
        if(tokenUntil.validateToken(claims)){
            throw new JwtException("token过期");
        }
        Long id = tokenUntil.getIdByToken(request);
        Object o = redisCache.getCacheObject("token:" + id);
        if(o==null){
            throw new JwtException("token过期");
        }
        String username=claims.getSubject();
        //获取用户的权限信息

        UsernamePasswordAuthenticationToken securityToken=new UsernamePasswordAuthenticationToken(username,null,userDetailService.getUserAuthorities(id));
        SecurityContextHolder.getContext().setAuthentication(securityToken);

        chain.doFilter(request,response);
    }
}
